import axios from "axios";
import { data } from "react-router-dom";

// 获取当前定位城市信息
export const getCurrenCity = () => {
  const localCity = JSON.parse(localStorage.getItem("hkzf_city"));

  // 如果没有就获取定位城市并且存储到本地，然后返回该城市数据
  if (!localCity) {
    if (navigator.geolocation) {
      return new Promise((resolve, reject) => {
        try {
          navigator.geolocation.getCurrentPosition(function (res) {
            // console.log(res); // 需要的坐标地址就在res中
            // longitude 经度；latitude 维度
            if (res.coords.longitude && res.coords.latitude) {
              const params = {
                key: "6aae8eb1ea15d5e7ca50af4b079c7687",
                location:
                  res.coords.longitude.toFixed(6) +
                  "," +
                  res.coords.latitude.toFixed(6),
                extensions: "all",
              };
              axios
                .get("https://restapi.amap.com/v3/geocode/regeo", { params })
                .then((res) => {
                  //   console.log("地理位置", res);
                  if (res.status === 200) {
                    // 获取当前城市信息
                    const name = res.data.regeocode.addressComponent.city;
                    axios
                      .get("http://localhost:8080/area/info", {
                        params: { name },
                      })
                      .then((res) => {
                        const data = res.data.body;
                        if (res.status === 200) {
                          localStorage.setItem(
                            "hkzf_city",
                            JSON.stringify(data)
                          );
                        }
                      });

                    resolve(data);
                  }
                });
            }
          });
        } catch (error) {
          reject(error);
        }
      });
    } else {
      alert("该浏览器不支持定位");
    }
  } else {
    return Promise.resolve(localCity);
  }
};
